#include <stdio.h>
#include <stdlib.h>

#include "highscores.h"
#include "parameters.h"
#include "video-graphics.h"


void printScores(Score *highscores, byte_t *target, byte_t *table) {
  drawString("Highscores", 433, 234 - 32, 0, -1, 2, target, table);
  int y;
  draw_line(412, 234, 412, 534, 0, target);
  draw_line(611, 234, 611, 534, 0, target);
  for (y = 234; y <= 234 + 300; y+= 20)
    draw_line(412, y, 412 + 200 - 1, y, 0, target);

  int i;
  char scoreStr[10];
  char name[4];
  name[3] = '\0';
  for (i = 0, y = 254; i < N_SCORES; ++i, y += 20) {
    name[0] = highscores[i].letter1;
    name[1] = highscores[i].letter2;
    name[2] = highscores[i].letter3;
    drawString(name, 417, y - 16, 0, -1, 1, target, table);
    sprintf(scoreStr, "%05lu", highscores[i].score);
    drawString(scoreStr, 568, y - 16, 0, -1, 1, target, table);
  }
}

/*
 * Bubble Sort Algorithm
 */
void sortScores(Score *highscores) {
  int i, j;
  bool_t swapped;
  Score temp;
  int n = N_SCORES;
  for (i = n - 1; i > 0; --i) {
    swapped = true;
    for (j = 0; i > j; ++j) {
      swapped = false;
      temp = highscores[j];
      highscores[j] = highscores[j + 1];
      highscores[j + 1] = temp;
    }
    if (swapped)
      break;
  }
}

bool_t loadScores(char *file, Score *highscores) {
  FILE *fp;
  if ((fp = fopen(file,"r")) == NULL)
    return false;
  int i;
  for (i = 0; i < N_SCORES; ++i) {
    fscanf(fp, "%c", &highscores[i].letter1);
    fscanf(fp, "%c", &highscores[i].letter2);
    fscanf(fp, "%c", &highscores[i].letter3);
    fscanf(fp, "%lu", &highscores[i].score);
  }
  fclose(fp);
  
  return true;
}

void saveScores(char *file, Score *highscores) {
  FILE *fp;
  if ((fp = fopen(file, "w")) == NULL) {
    printf("Error saving highscores.\n");
    exit(1);
  }
  int i;
  for (i = 0; i < N_SCORES; ++i) {
    fprintf(fp, "%c%c%c", highscores[i].letter1, highscores[i].letter2, highscores[i].letter3);
    fprintf(fp, "%lu", highscores[i].score);
  }
}
